package ocg.common.re.jdbc;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * Created by chenbo on 2018/3/1.
 * create database link
 */
public class JdbcBuilder {

    Logger logger = LogManager.getLogger ( this.getClass () );

    private String sqlDriver ;
    private String url ;
    private String username ;
    private String password ;

    private Connection connection;

    public JdbcBuilder(){

    }

    /**
     * 通过 url 判断数据库类型，返回相应的 driver 类型
     * @param url               数据库链接
     * @param username          数据库用户名
     * @param password          数据库密码
     */
    public JdbcBuilder(String url, String username, String password) {
        this.url = url;
        this.username = username;
        this.password = password;

        if ( url != null) {
            String[] uri = url.split ( ":" );
            if ( uri[1].equals ( "sqlserver" )) {
                this.sqlDriver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
                logger.info ( "当前使用 Sql Server 数据库链接 : " + url  );
            }
            if (uri[1].equals("mysql")){
                this.sqlDriver = "com.mysql.cj.jdbc.Driver";
                logger.info ( "当前使用 mysql 数据库链接 : " + url  );
            }
        }else {
            logger.error ( "数据库链接参数不正确 ：" + url );
        }
    }

    /**
     * create database link
     * create singleton , Ensure that the project has only one database link.
     * @return Connection
     */
    public Connection build(){
        if (connection == null) {
            synchronized (this) {
                if (connection == null) {
                    try {
                        Class.forName ( sqlDriver );
                        connection = DriverManager.getConnection ( url ,username ,password );
                        logger.info ( "数据库链接 创建成功！" );
                    } catch (SQLException e) {
                        logger.info ( "数据库链接 创建失败！SQLException ！" );
                        e.printStackTrace ();
                    } catch (ClassNotFoundException e) {
                        logger.info ( "数据库链接 创建失败！ClassNotFoundException ！" );
                        e.printStackTrace ();
                    }
                }
            }
        }
        return connection;
    }

    public void close(){
        if ( connection != null) {
            try {
                this.connection.close();

            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

